package com.zchat.api.http;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map;

import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

import com.zchat.api.error.ZChatConnectionException;
import com.zchat.api.log.Logger;

/**
 * 处理http连接
 * @author Oliverzhu
 *
 */
public class ZChatHttpHandler extends AbstractHttpApi {

	public ZChatHttpHandler(DefaultHttpClient httpClient, String clientVersion) {
		super(httpClient, clientVersion);
	}
	
	public static synchronized InputStream sendRequest(String url) throws ZChatConnectionException {
		HttpURLConnection httpConnection = null;
		try {
			int currentSize = 0;
			
			if(DEBUG) Logger.debug("req url : " + url);
			if(url == null) {
				return null;
			}
			URL uri = new URL(url);
			httpConnection = (HttpURLConnection)uri.openConnection();
            httpConnection.setRequestProperty("User-Agent", "PacificHttpClient");
            if(currentSize > 0) {
                httpConnection.setRequestProperty("RANGE", "bytes=" + currentSize + "-");
            }
			//设置超时时间
			httpConnection.setConnectTimeout(TIMEOUT);// 限制连接超时5秒钟
			httpConnection.setReadTimeout(2*TIMEOUT);
			httpConnection.setRequestProperty("Content-type",
					"text/html;charset=UTF-8");

			httpConnection.setDoOutput(true);
			httpConnection.setRequestMethod("GET");
			httpConnection.setUseCaches(false);

			//filter input stream
			
			int length = httpConnection.getContentLength();
			if(DEBUG) Logger.debug("save length:" + length);
			
			int requestCode = httpConnection.getResponseCode();
			if (requestCode == 200) {
				InputStream in = httpConnection.getInputStream();
				Logger.debug("save size:" + in.available());
				
				return in;
			}
		} catch (ProtocolException e) {
			e.printStackTrace();
			if(DEBUG) Logger.error("Occur protocol error when send request : " + url + ". And exception is : " + e.getMessage());
			throw new ZChatConnectionException("ProtocolException");
		} catch (IOException e) {
			e.printStackTrace();
			if(DEBUG) Logger.error("Occur io error when send request : " + url + ". And exception is : " + e.getMessage());
			throw new ZChatConnectionException("IOException");
		}
//		finally {
//			if(httpConnection != null) {
//				httpConnection.disconnect();
//			}
//		}
		return null;
	}
	
	public static int postFile(String actionUrl, String fileName, File file) 
			throws ZChatConnectionException {
		 
        String BOUNDARY = java.util.UUID.randomUUID().toString();		//用来标记每次发送的内容不是一样的，跳过程序的重复提交判断
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";

        // 得到响应码
		int res = 0;
		try {
			URL uri = new URL(actionUrl);
			HttpURLConnection conn = (HttpURLConnection) uri.openConnection();   
			conn.setReadTimeout(10 * 1000); 
			conn.setDoInput(true);// 允许输入
			conn.setDoOutput(true);// 允许输出
			conn.setUseCaches(false); 
			conn.setRequestMethod("POST");  //Post方式
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Charsert", "UTF-8");
			
			conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA+ ";boundary=" + BOUNDARY); 
			
			//输出流
			DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); 

			// 发送文件数据
			if (file != null){ 
			        StringBuilder sb1 = new StringBuilder();
			        sb1.append(PREFIX);
			        sb1.append(BOUNDARY);
			        sb1.append(LINEND);
			        //actionData 是自己定义的
			        sb1.append("Content-Disposition: form-data; name=\"actionData\"; filename=\""
			                        + fileName + "\"" + LINEND);
			        sb1.append("Content-Type: application/octet-stream; charset="
			                + CHARSET + LINEND);
			        sb1.append(LINEND);
			        
			        Log.e("info","2 :"+sb1.toString());

			        outStream.write(sb1.toString().getBytes());

			        InputStream is = new FileInputStream(file);
			        byte[] buffer = new byte[1024];
			        int len = 0;
			        while ((len = is.read(buffer)) != -1) {
			            outStream.write(buffer, 0, len);
			        }

			        is.close();
			        outStream.write(LINEND.getBytes());
			}   
			
			// 请求结束标志
			byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
   // 	  Log.e("info","3 :"+(new String(end_data,0,end_data.length)));

			outStream.write(end_data);
			outStream.flush();
			res = conn.getResponseCode(); 

			outStream.close();
			conn.disconnect();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ZChatConnectionException("使用post的方式上传文件出错!!");
		}
        return  res;
    
	}
	
	public static int postParams(String actionUrl, Map<String, String> params) 
			throws ZChatConnectionException {

    	Log.i("info", "actionUrl: "+actionUrl);
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";

        // 得到响应码
		int res = 0;
		try {
			URL uri = new URL(actionUrl);
			HttpURLConnection conn = (HttpURLConnection) uri.openConnection();        
			
			conn.setReadTimeout(5 * 1000); 
			conn.setDoInput(true);// 允许输入
			conn.setDoOutput(true);// 允许输出
			conn.setUseCaches(false); 
			conn.setRequestMethod("POST");  //Post方式
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Charsert", "UTF-8");
			
			conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
			        + ";boundary=" + BOUNDARY);

			
			// 首先组拼文本类型的参数
			StringBuilder sb = new StringBuilder();
			for (Map.Entry<String, String> entry : params.entrySet()) {
			    sb.append(PREFIX);
			    sb.append(BOUNDARY);
			    sb.append(LINEND);
			    sb.append("Content-Disposition: form-data; name=\""
			            + entry.getKey() + "\"" + LINEND);
			    sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
			    sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
			    sb.append(LINEND);
			    sb.append(entry.getValue());
			    sb.append(LINEND);
			}    
			
			DataOutputStream outStream = new DataOutputStream(conn
			        .getOutputStream());
			outStream.write(sb.toString().getBytes());
			
			
			// 请求结束标志
			byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
			outStream.write(end_data);
			outStream.flush();
			res = conn.getResponseCode(); 
     
			outStream.close();
			conn.disconnect();
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ZChatConnectionException("使用post的方式提交表单出错!!");
		}
        return res;
    
	}

}
